package com.ermax.aircond.manage.web.bean;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ermax.aircond.maintain.domain.Building;
import com.ermax.aircond.maintain.domain.Floor;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.domain.Room;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.manage.domain.RealTimeControl;
import com.ermax.aircond.manage.service.RealTimeControlService;
import com.ermax.aircond.resource.MessageBundle;

@Scope("view")
@Component
public class RealTimeManageBean implements java.io.Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(RealTimeManageBean.class);

	
	@Autowired
	private MaintainService maintainService;	
	@Autowired
	private RealTimeControlService realTimeControlService;
	@ManagedProperty(value = "#{loginBean.sessionUser}")
	private String sessionUser;	
	
	private Room selectedRoom;
	private List<RealTimeControl> realTimeControls;
	private RealTimeControl realTimeControl;
	private boolean allowControl = false;
	
	private List<SelectItem> buildingOptions = new ArrayList<SelectItem>();
	private List<SelectItem> floorOptions = new ArrayList<SelectItem>();
	private List<SelectItem> roomOptions = new ArrayList<SelectItem>();
	private List<SelectItem> temperatureOptions = new ArrayList<SelectItem>();
	private List<SelectItem> windValueOptions = new ArrayList<SelectItem>();
	private long selectedBuildingId;
	private long selectedFloorId;
	private long selectedRoomId;
	
	@PostConstruct
	public void init() {
		try {			
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}

	private void reset() throws Exception {		
		selectedBuildingId = 0;
		selectedFloorId = 0;
		selectedRoomId = 0;
		buildingOptions = createBuildingOptions();
		floorOptions = createFloorOptions();
		roomOptions = createRooomOptions();
		temperatureOptions = createTemperatureOptions();
		windValueOptions = createWindValueOptions();
		selectedRoom = new Room();
		realTimeControl = new RealTimeControl();
		realTimeControls = new ArrayList<RealTimeControl>();
		allowControl = false;
	}
	
	public void search() {
		try{									
			if(selectedRoomId > 0){
				selectedRoom = maintainService.getRoomById(selectedRoomId);				
				realTimeControls = realTimeControlService.getRealTimeControls(selectedRoom);
				allowControl = true;
			}
						
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}	
	
	public void send(){
		try{									
			if(selectedRoomId > 0){
				selectedRoom = maintainService.getRoomById(selectedRoomId);				
				realTimeControlService.sendRealTimeSignal(selectedRoom, realTimeControl);				
				Thread.sleep(500);
				realTimeControls = realTimeControlService.getRealTimeControls(selectedRoom);
				reset();
				String message = MessageBundle.getInstance().getMessage("info_apply_success", FacesContext.getCurrentInstance().getViewRoot().getLocale());
				FacesMessage facesMessage = new FacesMessage(message);
				FacesContext.getCurrentInstance().addMessage(null, facesMessage);
			}
						
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_apply_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
		
		
	}
	
	public void buildingValueChanged(ValueChangeEvent event) {      
        if (null != event.getNewValue()) {            
        	selectedFloorId = 0;
        	selectedRoomId = 0;
            selectedBuildingId = (Long) event.getNewValue();            
            floorOptions = createFloorOptions();
            roomOptions = createRooomOptions();
        }
    }
	
	public void floorValueChanged(ValueChangeEvent event) {      
        if (null != event.getNewValue()) {  
        	selectedRoomId = 0;
            selectedFloorId = (Long) event.getNewValue();
            roomOptions = createRooomOptions();
        }
    }
	
	public void roomValueChanged(ValueChangeEvent event) {
		allowControl = false;
		if (null != event.getNewValue()) {
			selectedRoomId = (Long) event.getNewValue();
			if (selectedRoomId > 0) {
				allowControl = true;
			}
		}
	}
	
	private List<SelectItem> createBuildingOptions() {
		List<SelectItem> results = new ArrayList<SelectItem>();	
		results.add(new SelectItem(0,"------"));
		try {
			List<Building> buildings = maintainService.getAllBuildings();
			for (Building building : buildings) {
				SelectItem item = new SelectItem(building.getBuildingId(), building.getBuildingName());
				results.add(item);
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		return results;
	}
	
	private List<SelectItem> createFloorOptions(){		
		List<SelectItem> results = new ArrayList<SelectItem>();	
		results.add(new SelectItem(0,"------"));
			
		try{
			if(selectedBuildingId > 0){
				Building selectedBuilding = maintainService.getBuildingById(selectedBuildingId);
				List<Floor> floors = maintainService.getFloors(selectedBuilding);
	        	for(Floor floor : floors){
	        		SelectItem item = new SelectItem(floor.getFloorId(), floor.getFloorName());
	        		results.add(item);
	        	}
			}
		}catch (Exception e) {
			logger.error(e.getMessage());
		}			
		return results;		
	}
	
	private List<SelectItem> createRooomOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		results.add(new SelectItem(0,"------"));
		try{
			if(selectedFloorId > 0){
				Floor selectedFloor = maintainService.getFloorById(selectedFloorId);
				List<Room> rooms = maintainService.getRooms(selectedFloor);
				for(Room room : rooms){
					SelectItem item = new SelectItem(room.getRoomId(), room.getRoomName());
					results.add(item);
				}
			}
		}catch(Exception e){
			logger.error(e.getLocalizedMessage());
		}
		return results;
	}
	
	private List<SelectItem> createTemperatureOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		for(int i=16; i<=32; i++){
			results.add(new SelectItem(i,String.valueOf(i)));
		}
		return results;
	}
	
	private List<SelectItem> createWindValueOptions(){
		List<SelectItem> results = new ArrayList<SelectItem>();
		int i = 0;
		while(i <= 100){
			results.add(new SelectItem(i,String.valueOf(i)));
			i += 5;
		}
		
		return results;
	}
		

	public MaintainService getMaintainService() {
		return maintainService;
	}

	public void setMaintainService(MaintainService maintainService) {
		this.maintainService = maintainService;
	}

	public String getSessionUser() {
		return sessionUser;
	}

	public void setSessionUser(String sessionUser) {
		this.sessionUser = sessionUser;
	}

	public Room getSelectedRoom() {
		return selectedRoom;
	}

	public void setSelectedRoom(Room selectedRoom) {
		this.selectedRoom = selectedRoom;
	}

	public List<SelectItem> getBuildingOptions() {
		return buildingOptions;
	}

	public void setBuildingOptions(List<SelectItem> buildingOptions) {
		this.buildingOptions = buildingOptions;
	}

	public List<SelectItem> getFloorOptions() {
		return floorOptions;
	}

	public void setFloorOptions(List<SelectItem> floorOptions) {
		this.floorOptions = floorOptions;
	}

	public List<SelectItem> getRoomOptions() {
		return roomOptions;
	}

	public void setRoomOptions(List<SelectItem> roomOptions) {
		this.roomOptions = roomOptions;
	}

	public long getSelectedBuildingId() {
		return selectedBuildingId;
	}

	public void setSelectedBuildingId(long selectedBuildingId) {
		this.selectedBuildingId = selectedBuildingId;
	}

	public long getSelectedFloorId() {
		return selectedFloorId;
	}

	public void setSelectedFloorId(long selectedFloorId) {
		this.selectedFloorId = selectedFloorId;
	}

	public long getSelectedRoomId() {
		return selectedRoomId;
	}

	public void setSelectedRoomId(long selectedRoomId) {
		this.selectedRoomId = selectedRoomId;
	}
	

	public boolean isAllowControl() {
		return allowControl;
	}

	public void setAllowControl(boolean allowControl) {
		this.allowControl = allowControl;
	}

	public List<RealTimeControl> getRealTimeControls() {
		return realTimeControls;
	}

	public void setRealTimeControls(List<RealTimeControl> realTimeControls) {
		this.realTimeControls = realTimeControls;
	}

	public RealTimeControlService getRealTimeControlService() {
		return realTimeControlService;
	}

	public void setRealTimeControlService(RealTimeControlService realTimeControlService) {
		this.realTimeControlService = realTimeControlService;
	}

	public List<SelectItem> getTemperatureOptions() {
		return temperatureOptions;
	}

	public void setTemperatureOptions(List<SelectItem> temperatureOptions) {
		this.temperatureOptions = temperatureOptions;
	}

	public List<SelectItem> getWindValueOptions() {
		return windValueOptions;
	}

	public void setWindValueOptions(List<SelectItem> windValueOptions) {
		this.windValueOptions = windValueOptions;
	}

	public RealTimeControl getRealTimeControl() {
		return realTimeControl;
	}

	public void setRealTimeControl(RealTimeControl realTimeControl) {
		this.realTimeControl = realTimeControl;
	}
	
}
